#!/usr/bin/python
# -*- coding: utf-8 -*-
import gtk
from gtk import gdk

def units(bytes):
    pref = " KMGT"
    bytes = float(bytes)
    for x in xrange(5):
        d = 10**(x*3)
        if bytes < d*1024:
            return "%s%sB" % (bytes/d % 1 and round(bytes/d, 1) or int(bytes/d), pref[x])
	
def unic(string):
    """'Failsafe' unicode."""
    # What character should be used here?
    try: 
        return unicode(string, 'utf8')
    except UnicodeDecodeError:
        return unicode(string, 'iso8859', 'replace')

gtk_fiddle_count = 0
def threads(method):
    """GTK+ lock thread decorator.
    
    To prevent that gtk.gdk.threads_enter and threads_leave
    will be called more than twice we use a semaphore-like counter
    of threads that are fiddling with the gtk internals.
    """
    def add_gdk_calls(*args, **kwargs):
        global gtk_fiddle_count
        gtk_fiddle_count += 1
        if not gtk_fiddle_count > 1:
            gdk.threads_enter()
        method(*args, **kwargs)
        gtk_fiddle_count -= 1
        if gtk_fiddle_count == 0:
            gdk.threads_leave()
    return add_gdk_calls

def iters_selection(selection):
    """Returns a list of all iters selected in gtk.TreeSelection."""
    i = []
    def a(t, p, it):
        i.append(it)
    selection.selected_foreach(a)
    return i
